﻿#region The MIT License
// The MIT License
// 
// Copyright (c) 2009 octalforty studios
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration.Install;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Configuration;
using System.ServiceModel.Description;
using System.ServiceProcess;
using System.Text;
using System.Xml;

using Autofac;

using octalforty.Chinchillin.Actions.Db;
using octalforty.Chinchillin.Agent.Core;
using octalforty.Chinchillin.Agent.Core.Deployment;
using octalforty.Chinchillin.Agent.Core.Deployment.Impl;
using octalforty.Chinchillin.Agent.Core.Tracing.Impl;
using octalforty.Chinchillin.Agent.Support.ServiceModel;
using octalforty.Chinchillin.Shared.Deployment.Agent;
using octalforty.Chinchillin.Shared.Deployment.Resources;
using octalforty.Chinchillin.Shared.Deployment.Resources.Impl;
using octalforty.Chinchillin.Shared.Tracing;

namespace octalforty.Chinchillin.Agent
{
    static class Program
    {
        public static IContainer container;
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            if(args.Contains("/install"))
            {
                using(var installer = new TransactedInstaller())
                {
                    var assemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location;

                    installer.Installers.Add(new ProjectInstaller());
                    installer.Context = new InstallContext("", null) { Parameters = { { "assemblypath", assemblyPath } } };
                    
                    installer.Install(new Hashtable());
                } // using

                return;
            } // if

            if(args.Contains("/uninstall"))
            {
                using(var installer = new TransactedInstaller())
                {
                    var assemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location;

                    installer.Installers.Add(new ProjectInstaller());
                    installer.Context = new InstallContext("", null) { Parameters = { { "assemblypath", assemblyPath } } };
                    
                    installer.Uninstall(null);
                } // using

                return;
            } // if

            if(args.Contains("/service"))
            {
                var services = new ServiceBase[] { new ChinchillinService() };
                ServiceBase.Run(services);

                return;
            }

            /*ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
			{ 
				new ChinchillinService() 
			};
            ServiceBase.Run(ServicesToRun);*/
            //
            // Fuckin'
            // netsh -c http add urlacl url=http://+:8080/chinchillin user=domain\user

            //
            // MEX Programmatically
            // http://msdn.microsoft.com/en-us/library/aa738489.aspx
            using(var container = CreateContainer())
            {
                using(var serviceHost = new AutofacServiceHost<DeploymentAgentService>((IServiceProvider)container))
                {
                    /*var binding = new WSDualHttpBinding(WSDualHttpSecurityMode.None)
                        {
                            SendTimeout = TimeSpan.FromMinutes(5),
                            ReceiveTimeout = TimeSpan.FromMinutes(5),
                            MaxReceivedMessageSize = 16000000,
                            MaxBufferPoolSize = long.MaxValue,
                            ReaderQuotas = XmlDictionaryReaderQuotas.Max,
                            UseDefaultWebProxy = true,
                        };
                    serviceHost.AddServiceEndpoint(typeof(IDeploymentAgentService), binding, new Uri("http://192.168.0.98:8080/chinchillin"));
                    ((ServiceDebugBehavior)serviceHost.Description.Behaviors[typeof(ServiceDebugBehavior)]).IncludeExceptionDetailInFaults = true;
                    var smb = serviceHost.Description.Behaviors.Find<ServiceMetadataBehavior>();
                    if(smb == null)
                        serviceHost.Description.Behaviors.Add(smb = new ServiceMetadataBehavior());
                    smb.HttpGetUrl = new Uri("http://192.168.0.98:8080/chinchillin/get");
                    smb.HttpGetEnabled = true;*/

                    //serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), new BasicHttpBinding(), new Uri("http://localhost:8080/chinchillin/mex"));

                    serviceHost.Open();

                    Console.WriteLine("Listening...");
                    Console.ReadLine();
                } // using
            } // using

        }

        public static IContainer CreateContainer()
        {
            var containerBuilder = new ContainerBuilder();

            containerBuilder.
                Register(c => OperationContext.Current.GetCallbackChannel<IDeploymentCallback>()).
                    As<IDeploymentCallback>().
                    InstancePerDependency().
                    PropertiesAutowired();

            containerBuilder.
                RegisterType<DeploymentAgentService>().
                    //As<IDeploymentAgentService>().
                    InstancePerDependency().
                    PropertiesAutowired();

            containerBuilder.
                RegisterModule(new ActionRegistryModule());

            containerBuilder.
                RegisterModule(new DbPlatformRegistryModule());

            containerBuilder.
                RegisterType<ActionRuntimeService>().
                    As<IActionRuntimeService>().
                    InstancePerDependency().
                    PropertiesAutowired();

            containerBuilder.
                RegisterType<FileSystemResourceProvider>().
                    As<IResourceProvider>().
                    InstancePerDependency().
                    PropertiesAutowired();

            containerBuilder.
                RegisterType<FileSystemManager>().
                    As<IFileSystemManager>().
                    InstancePerDependency().
                    PropertiesAutowired();

            containerBuilder.
                RegisterType<Sha1ChecksumProvider>().
                    As<IChecksumProvider>().
                    InstancePerDependency().
                    PropertiesAutowired();

            containerBuilder.
                RegisterType<TracingManagerService>().
                    As<ITracingManagerService>().
                    InstancePerDependency().
                    PropertiesAutowired();

            return containerBuilder.Build();
        }
    }
}
